<template>
	<div class="enclosure-list">
		<div class="publishFrom enclosure">
			<div class="publishFrom_ad buttonCSS">
				<el-button  size="primary" @click="addFileBox">添加附件</el-button>
				<el-button  size="danger" @click="deleteMuilt_confirm">删除所选</el-button>
			</div>
			<template>
				<el-table
				ref="multipleTable"
				:data="listData"
				tooltip-effect="dark"
				style="width: 100%"
				border
				v-loading="loading.status"
		  	:element-loading-text="loading.txt"
				@selection-change="tableSelectionChange">
					<el-table-column
						type="selection"
						align="center"
						width="50"
            fixed>
					</el-table-column>
					<el-table-column
						prop="name"
						label="附件名称"
						 align="center"
						width="120">
					</el-table-column>
					<el-table-column
						prop="postfix"
						label="附件类型"
						 align="center"
						width="80">
					</el-table-column>
					<el-table-column
						prop="create_time"
						width="150"
                        align="center"
						label="上传时间"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
						prop="comment"
						label="备注"
						 align="center"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
					    label="操作"
					    align="center"
					    width="160">
					    <template slot-scope="scope">
					       <el-button @click="editFileBox(scope.row)" type="text" size="small">编辑</el-button>
					       <el-button @click="down(scope.row.path,scope.row.name)" type="text" size="small">下载</el-button>
					      <el-button @click="delete_confirm(scope.row)" type="text" class="delete-button" size="small">删除</el-button>
					    </template>
					  </el-table-column>
				</el-table>
			</template>
			<div class="pageBox" v-show="total_number > 10">
				<el-pagination
				    @size-change="handleSizeChange"
				    @current-change="handleCurrentChange"
				    :current-page="listParam.page_index"
				    :page-size="listParam.page_size"
				    layout="total,  prev, pager, next, jumper"
				    :total="total_number">
				</el-pagination>
			</div>
		</div>
		<!-- 添加附件 -->
		<el-dialog
			:title="fileTitle"
			:visible.sync="addAttachments"
			width="800px"
			custom-class="addAttachments"
			:before-close="resetForm"
			:close-on-press-escape="false"
			:close-on-click-modal="false">
			<div class="addAttachments-c">
				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="上传附件" prop="select_or_not" v-if="parseInt(ruleForm.id) === 0 ">
						 <uploader 
						 :options="uploadOptions" 
						 :autoStart="false" 
						 ref="uploader" 
						 :file-status-text="statusText" 
						 @file-added="fileAdd" 
						 @file-removed="fileRemoved" 
						 @file-success="fileSuccess" 
						 @file-error="fileFail"  
						 class="uploader-example">
						    <uploader-unsupport></uploader-unsupport>
						    <uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">
						    	<span>选择文件</span>
						    </uploader-btn>
						    <uploader-list  v-if="selectFileShow===false?true:false"></uploader-list>
						 </uploader>
					</el-form-item>
					<el-form-item label="权限" prop="authority">
						<el-radio-group v-model="ruleForm.authority">
							<el-radio label="1">公开</el-radio>
							<el-radio label="0">不公开</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="附件名称" prop="name">
						<el-input v-model.trim="ruleForm.name" maxlength="20" placeholder="请输入附件名称"></el-input>
					</el-form-item>
					<el-form-item label="附件备注" prop="comment">
						<el-input type="textarea" v-model="ruleForm.comment"
						:rows="5"
						resize="none"
						maxlength="200"
						placeholder="请输入附件备注,不超过200个字符"></el-input>
						<span class="numberWord">{{ ruleForm.comment.length }}/200</span>
					</el-form-item>
				</el-form>
				<div style="padding-left: 100px">										
					<el-button @click="resetForm('ruleForm')">取消</el-button>
					<el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
    import {uploaderFileFail} from './../../../../tools/tool';

	export default {
		props : ['compParam','activeIndex'],
		name: '',
		data() {
			return {
        thisIndex:'6',
        fileTitle: '添加附件', // 弹窗标题
				total_number:0,
				statusText: {
			      	success: '上传成功',  
			      	error: '上传出错',  
			     	uploading: '正在上传...',  
			      	paused: '暂停',  
			      	waiting: '等待上传'  
				},
				selectFileOrNot:false,  //是否选中文件
			    uploadOrNot:false, 		//是否已经上传
			    uploadInfo:{
					file_name:'',
					file_path:'',
					file_size:0
				},
				attrs: {
			      	//accept: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/msword']
			    },
		    	uploadOptions: {
			          target: this.BASE_URL+'/api/resource/res_upload',
			          testChunks: false,
			          headers:{Authorization : `Bearer `+this.$g.access_token},
			    },
	            ruleForm: {
	            	id:0,
	            	video_id:0,
					name: '',
					authority:'1',
					comment:'',
					select_or_not:'',
				},
	      listParam:{
					videoid:0,
					page_index:1,
					page_size:10,
				},
	      selectFileShow:true,//是否显示选择文件按钮
				uploadRetryTimes:100,//文件最大重传次数
				selected: [],//表单checkbox
				listData: [],
				loading:{
					status:false,
					txt:'获取数据...',
				},
				addAttachments: false, //添加附件
				rules: {
					name: [
						{ required: true, message: '请输入附件名称', trigger: 'blur' },
						{ min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
					],
					select_or_not: [
		            	{ required: true,validator: this.validateName, message: '请选择文件'}
		            ],
				},
				rowLen: 0
			}
		},
		watch:{
			'activeIndex':{
	    		handler(n){
	    			if( n === this.thisIndex ){
	    				this.initFunc();
	    			}
	    		},
			},
			'addAttachments': {
				handler(n) {
					if(!n && this.ruleForm.id !== 0) {
						this.$refs.uploader.uploader.cancel();
					}
				}
			}
		},
		methods: {
			initFunc(){
				this.getList();
            },
            /**
             * 添加附件
             */
            addFileBox() {
                this.addAttachments = true;
                this.fileTitle = '添加附件';
                this.ruleForm = {
	            	id:0,
	            	video_id:0,
					name: '',
					authority:'1',
					comment:'',
					select_or_not:'',
				};
            },
			editFileBox( obj ){
        this.addAttachments = true;
        this.fileTitle = '编辑附件';
				this.ruleForm.id = obj.id;
				this.ruleForm.name = obj.name;
				this.ruleForm.authority = obj.authority.toString();
				this.ruleForm.comment = obj.comment;
			},
			getList(){
		    	this.loading.status = true;
		    	this.listParam.videoid = this.compParam.id;
		    	// 重写成功回调
				let success = ( data => {
					this.loading.status = false;
					this.listData = data.data.data;
					console.log(this.listData, 1234)

					this.total_number = data.data.data_sum;
				});
				let fail = ( data => {
					this.loading.status = false;
					this.$message.error(data.msg)
				})
  				this.$ajax.get('api/video/video_file_list',{params:this.listParam,func:{success:success,fail:fail}})
		    },
			saveFile(){
				let params = {};
					params.id = this.ruleForm.id;
					params.video_id = this.compParam.id;
					params.name =  this.ruleForm.name;
					params.authority =  this.ruleForm.authority;
          params.comment =  this.ruleForm.comment;
                    
					if( parseInt( this.ruleForm.id ) === 0 ){
						params.path = this.uploadInfo.file_path;
						params.size = this.uploadInfo.file_size;
						params.postfix = this.uploadInfo.post_fix;
					}
            	let success = ( data=>{
					this.$message.success(data.msg);
					this.addAttachments = false;
					this.getList();
					this.resetForm();
				})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	if( !is_empty( params.id ) && parseInt( params.id ) > 0 ){
            		this.$ajax.put('api/video/video_file',params,{func:{success:success}})
            	}else{
					this.$ajax.post('api/video/video_file',params,{func:{success:success}})
            	}
			},
			//上传成功的事件  
			fileSuccess (rootFile, file, message, chunk) { 
				this.$refs.uploader.uploader.cancel();
                var mess = eval('(' + message + ')');
                mess = handleResponseData( mess );
                
			 	if(parseInt( mess.data.status ) ===1 ){
			  		this.uploadOrNot = true;
			  		this.uploadInfo.file_name = mess.data.file_name;
			  		this.uploadInfo.file_path = mess.data.file_path;
			  		this.uploadInfo.post_fix = mess.data.post_fix;
			  		this.saveFile();
			  }
			},
			fileFail(rootFile, file, message, chunk) {
                uploaderFileFail(this, this.$refs.uploader.uploader, file, message);
			},
			fileAdd( file,fileList ){
                if (file.size > 2000 * 1024 * 1024) {
                    this.$message.error("附件大小不能超过2G");
                    file.ignored = true;
                    return false;
                }
				this.ruleForm.select_or_not = '1';
				this.uploadInfo.file_size = file.size;
				this.selectFileOrNot = true;
				this.selectFileShow = false;
			},
			fileRemoved(file){
				this.ruleForm.select_or_not = '';
				this.selectFileOrNot = false;
				this.selectFileShow = true;
            },
            /**
             * 保存之前先判断是否重名
             */
			fileUpload(){
				let success = (res => {
					this.$refs.uploader.uploader.upload();
				});
				let fail = (res => {
					this.$message.error(res.msg);
                })
                let params = {
                    name: this.ruleForm.name,
                    video_id: this.compParam.id,
                    postfix: this.$refs.uploader.fileList[0].name.split('.').pop()
                }

  				this.$ajax.get('api/video/check_video_file', {params: params, func: {success: success, fail: fail}});
			},
			handleSizeChange(val) {
		    	this.listParam.page_index = 1;
		    	this.listParam.page_size = val;
		    	this.getList()
		    },
		    handleCurrentChange(val) {
		    	this.listParam.page_index = val;
		    	this.getList();
		    },
			 //选中
		    tableSelectionChange(val) {
                this.selected = val;
            },
			//表单
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if( parseInt(this.ruleForm.id) > 0 ){
							this.saveFile();
						}else{
							this.fileUpload();
						}
					} else {
						return false;
					}
				});
			},
			resetForm() {
				this.$refs.ruleForm.clearValidate();
				this.addAttachments = false;
				this.selectFileShow = true;
                this.$refs.uploader.uploader.cancel();
				this.ruleForm =  {
	            	id:0,
	            	video_id:0,
					name: '',
					authority:'1',
					comment:'',
					select_or_not:'',
				};
			},
			 delete(id){
		    	let success = ( data => {
		    		this.$message.success(data.msg)
		    		
					if (this.listData.length - this.rowLen === 0) {
						if (this.listParam.page_index > 1) {
							this.listParam.page_index-- ;
						} else {
							this.listParam.page_index = 1;
						}
					}

					this.getList();
				});
		    	this.$ajax.delete('api/video/video_file',{params:{id:id},func:{success:success}})
		    },
		    delete_confirm(obj){
				let yes = ( data => {
					this.rowLen = 1;
					this.delete(obj.id);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 删除吗？'});

			},
			deleteMuilt_confirm(){
				if( this.selected.length === 0 ) {
					this.$message.warning("请选择要删除的项");
					return false;
				}
				let yes = ( data => {
					this.rowLen = this.selected.length;
					this.muilDelete();
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定要删除选中的项吗？'});

			},
			muilDelete(){
				var ids = [];
				for (var i = this.selected.length - 1; i >= 0; i--) {
					ids.push(this.selected[i].id)
				}
				this.delete(ids);
			},
			down(path,name){
	    		var form = document.createElement("form");
			    form.action = this.BASE_URL+'/index/resource/download_video_file';
			    form.method = 'post';
			    form.style.display = "none";
				
	            var opt_path = document.createElement("textarea");
	            opt_path.name = 'path';
	            opt_path.value = path;
	            form.appendChild(opt_path);
	            var opt_name = document.createElement("textarea");
	            opt_name.name = 'name';
	            opt_name.value = name;
	            form.appendChild(opt_name);
			    document.body.appendChild(form);
			    form.submit();
			    document.body.removeChild(form);
	    	},
		}
	}
</script>
<style lang="scss">
	.addAttachments-c{
		// padding:30px 30px 60px;
		text-align: left;
		padding-bottom: 30px;
		.urlTxt{
			font-size: 12px;
			color: #888;
			margin-left: 20px;
			max-width: 300px;
		}
	}
	.r_fileBox{
		display: inline-block;
		vertical-align: top;
	}
	.r_file {
	    width: 80px;
	    height: 36px;
	    background: #338efc;
	    border-radius: 3px;
	    line-height: 36px;
	    color: #ffffff;
	    text-align: center;
	    font-size: 14px;
	    display: inline-block;
	    vertical-align: top;
	    cursor: pointer;
	}

	.confirm-them{
		width: 520px;
		border-radius: 0;
		border:0;
		padding-bottom: 20px;
		.el-message-box__header{
			background: #409EFF;
			padding: 15px;
			.el-message-box__title,
			.el-message-box__close{
				color: #fff;
			}
		}
		.el-message-box__content{
			padding: 60px 20px;
		}
		.el-message-box__btns{
			>button{
				padding: 0;
				border:0;
				width: 80px;
				height: 30px;
				line-height: 30px;
				text-align: center;
				&:nth-of-type(1){
					background: #DEEFFF;
					color: #7C9BB8;
				}
			}
		}
	}

	.videoIntegration_tm{
		.el-form-item{
			float: left;
			.el-input{
				width: 170px;
			}
			.el-icon-location{
				font-size: 20px;
				color: #348efc;
				padding: 10px;
				background: #E8F2FF;
				border-radius: 3px;
				vertical-align: middle;
				cursor: pointer;
			}
		}
		.t_length{
			font-size: 20px;
			color: #348EFC;
		}
	}
	.enclosure {
		.el-dialog__wrapper {
			text-align: left;
		}
	}

    .enclosure-list {
        .uploader-file-name {
            width: 40%;
        }
        
        .uploader-file-meta {
            width: 5%;
        }
        .uploader-file-status {
            width: 32%;
            
        }
    }
</style>